-- UIReagent
-- Create by chendh
-- 试剂工坊界面

require "game/ui/form/reagent/UIReagentDetail"

-- UIReagent继承自Layer
UIReagent = class("UIReagent", function()
    return cc.Layer:create();
end);

function UIReagent.create()
    return UIReagent.new();
end

-- 商品格最大行数和列数
local MAX_GRID_ROW    = 2;
local MIN_GRID_COLUMN = 3;
local MAX_TAB_NUM = 6;

-- 内部函数声明

-- 构造函数
function UIReagent:ctor()
    -- 初始化
    self:setName("UIReagent");
    local node = cc.CSLoader:createNode("layout/workshop/WorkshopStore.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");
    local scrollview = CT:getChildByName("scrollview");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 检查是否有新的试剂
    ReagentM.checkReagent();

    -- 初始化数据
    self:initData();

    -- 默认选中页签1
    self:initTabs();
    if #self.tabList > 0 then
        self:selectTab(self.tabList[1]:getTag());
    end

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIReagent:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化数据
function UIReagent:initData()
    local data = {};

    for i = 1, MAX_TAB_NUM do
        table.insert(data, self:gatherGoodsInfo(i));
    end

    self.data = data;
end

-- 初始化页签
function UIReagent:initTabs()
    self.tabList = {};

    local startY = 0;
    local gap = 100;

    for i = 1, MAX_TAB_NUM do
        local tab = findChildByName(self.node, "CT/tab"..i);
        tab:setTag(i);
        local tabIcon = findChildByName(tab, "tab_icon");
        tabIcon:loadTexture(getWorkshopIconPath(tostring(i)));

        if startY == 0 and i == 1 then
            startY = tab:getPositionY();
        end

        if #self.data[i] > 0 then
            table.insert(self.tabList, tab);
            tab:setVisible(true);
        else
            tab:setVisible(false);
        end

        tab:addTouchEventListener(function (sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                -- 选中页签处理
                self:selectTab(sender:getTag());
            end
        end);
    end

    for i = 1, #self.tabList do
        local tab = self.tabList[i];
        tab:setPositionY(startY - (i - 1) * gap);
    end
end

-- 改变页签状态
function UIReagent:selectTab(index)
    self.selectIndex = index;

    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;
    for i = 1, #self.tabList do
        local tab = self.tabList[i];
        if index == tab:getTag() then
            tab:setColor(normalColor);
        else
            tab:setColor(blendColor);
        end
    end

    -- 初始化商品格子
    self:initGoodsGrids();

    self:redraw();

    -- 默认滑到最顶端
    scrollToTop(self.scrollView);
end

-- 初始化商品格
function UIReagent:initGoodsGrids()
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 23;

    -- 图标间距(纵向)
    local hGap = 15;

    -- 图标宽度
    local iconWidth = 128;

    -- 图片高度
    local iconHeight = 153;

    local topHGap  = 10;
    local bottomHGap = 30;
    local leftWGap = 20;

    -- 收集商品信息
    local goodsList = self.data[self.selectIndex];

    -- 商品的共个数
    local shopCount = #goodsList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/shop/BlackMarketGoodsIcon.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param bottomHGap    下方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, shopCount, MAX_GRID_ROW, MIN_GRID_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, self.registerPetShopTouchEvent);
end

-- 清空所有的商品格
function UIReagent:clearAllGrid()
    -- 格子总数
    local totalGridCount = #self.data;
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            grid:setVisible(false);
        end
    end
end

-- 显示商店
function UIReagent:redraw()
    -- 显示标题
    local titleLabel = findChildByName(self.CT, "title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("reagent"));

    -- 提示信息
    local subheadLabel = findChildByName(self.CT, "subhead");
    TextStyleM.setSubheadStyle(subheadLabel);
    subheadLabel:setString(getLocStr("reagent_choice"));

    --标题背景
    local btTypeImg = findChildByName(self.node, "CT/bg_type");
    local btTypeImg2 = findChildByName(self.node, "CT/bg_type2");

    btTypeImg:loadTexture(getTitleBgIconPath("alchemy"));
    btTypeImg2:loadTexture(getTitleBgIconPath("alchemy"));

    -- 收集商品信息
    local goodsList = self.data[self.selectIndex];
    if not goodsList or #goodsList == 0 then
        cclog("收集商品信息失败。");
        self:clearAllGrid();
        return;
    end

    local totalGridCount = #goodsList;

    -- 显示商品信息
    local totalGoodsCount = #goodsList;
    for i = 1, totalGridCount do
        local grid          = self.scrollView:getChildByName("item" .. i);
        local goodsBg       = grid:getChildByName("bg");
        local iconImg       = grid:getChildByName("goods_icon");
        local moneyImg      = grid:getChildByName("money_icon");
        local moneyLabel    = grid:getChildByName("money_count");
        local soldOutLabel    = grid:getChildByName("sold_out");
        local rankNode      = grid:getChildByName("star_node");
        local countLabel     = grid:getChildByName("item_count");

        if i <= totalGoodsCount then
            grid:setVisible(true);

            local goodsIndex = goodsList[i][1];   -- 商品序号
            local goodsId    = goodsList[i][2];   -- 商品id
            local classId    = goodsList[i][3];   -- 宠物的class_id
            local goodsIcon  = goodsList[i][4];   -- 商品图标
            local payAttrib  = goodsList[i][5];   -- 支付属性
            local goodsPrice = goodsList[i][6];   -- 商品价格
            local itemName   = goodsList[i][7];   -- 物品名称
            local rank       = goodsList[i][8];   -- 阶位

            -- 为商品图标绑定信息
            iconImg.goodsIndex = goodsIndex;
            iconImg.goodsId    = goodsId;
            iconImg.classId    = classId;
            iconImg.goodsIcon  = goodsIcon;
            iconImg.payAttrib  = payAttrib;
            iconImg.goodsPrice = goodsPrice;
            iconImg.itemName   = itemName;
            iconImg.rank       = rank;

            -- 显示商品阶位
            local layer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.7);
            if layer then
                rankNode:removeAllChildren();
                rankNode:addChild(layer);
            end

            countLabel:setVisible(false);

            -- 显示商品图标
            iconImg:loadTexture(getItemIconPath(goodsIcon));

            -- 显示价格
            local offset = 0;
            local iconPath = getSmallAttribIconPath(FieldsM.query(payAttrib, "icon"));
            moneyImg:loadTexture(iconPath);
            moneyImg:setScale(40 / moneyImg:getContentSize().width);
            if not moneyImg.initPositionY then
                moneyImg.initPositionY = moneyImg:getPositionY();
                moneyImg:setPositionY(moneyImg:getPositionY() + 8);
            end

            TextStyleM.setTextStyle(moneyLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_WHITE, true);
            moneyLabel:setString(tostring(goodsPrice));
            moneyLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() - 2);
            if ME.user:queryAttrib(payAttrib) < goodsPrice then
                moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_LIGHT_RED);
            else
                moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_WHITE);
            end
            if not moneyLabel.initPositionY then
                moneyLabel.initPositionY = moneyLabel:getPositionY();
                moneyLabel:setPositionY(moneyLabel:getPositionY() + 8);
            end

            -- 居中显示
            local moneyImgW = moneyImg:getContentSize().width * moneyImg:getScaleX();
            local moneyLabelW = moneyLabel:getContentSize().width;
            -- 间隔
            local gap = 0;
            local s = (moneyImgW + moneyLabelW + gap) / 2;
            -- 位置调整
            moneyImg:setPositionX(-s - offset / 2 );
            moneyLabel:setPositionX(moneyImg:getPositionX() + offset + moneyImgW + gap);

            -- 如果商品已售完，显示图标

                -- 背景变亮
                setGrayTransMode(goodsBg, false);
                setGrayTransMode(iconImg, false);

                -- 显示图标、价格、星星
                moneyImg:setVisible(true);
                moneyLabel:setVisible(true);
                rankNode:setVisible(true);

                soldOutLabel:setVisible(false);
        else
            -- 清空多余的格子
            grid:setVisible(false);
        end
    end
end

-- 获取可购买的商品信息
function UIReagent:gatherGoodsInfo(rank)
    -- 获取本店的所有商品
    local goodsList = ReagentM.getAllReagents();
    if goodsList == nil then
        return {};
    end

    local ret = {};
    local goodsIndex = 1;  -- 商品的序号
    for _, info in ipairs(goodsList) do
        local goodsId    = info.id;
        local arr        = ReagentM.queryPrice(goodsId);
        local payAttrib  = arr[2];           -- 支付属性
        local goodsPrice = arr[3];           -- 商品价格
        --降低消耗的属性
        if arr[2] == "money" then
            local prop = PropM.combine(ME.user, "reagent_cost", 1);
            goodsPrice = PropM.apply(prop, goodsPrice);
        end
        local goodsinfo  = ReagentM.queryGoodsInfo(goodsId);
        local classId    = goodsinfo[2];
        local goodsCount = goodsinfo[3];      -- 商品数量
        local itemInfo   = ItemM.query(classId);
        if itemInfo and ReagentM.isReagentActive(goodsId) and itemInfo.rank == rank then
            table.insert(ret, {goodsIndex, goodsId, classId, itemInfo["icon"], payAttrib, goodsPrice,
                itemInfo["name"], itemInfo["rank"]});
        end

        goodsIndex = goodsIndex + 1;
    end

    return ret;
end

-- 注册商品点击事件
function UIReagent:registerPetShopTouchEvent(node)
    -- 注册商品图标点击事件
    local image = node:getChildByName("bg");
    local iconImg = node:getChildByName("goods_icon");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_spell");
            -- 仅处理非空的格子
            if type(iconImg.goodsIcon) == 'number' then
                self:onGoodsClick(iconImg);
            end
        end
    end
    image:addTouchEventListener(onClick)
end

-- 注册事件处理回调函数
function UIReagent:registerEventCallback()

    -- 关注购买商品的事件
    EventMgr.register("UIReagent", event.REAGENT_BUY_GOODS, function(args)
        self:whenBuyGoods(args.classId, args.amount);
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIReagent", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIReagent" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
        end
    end);

    -- 注册新试剂激活的回调
    EventMgr.register("UIReagent", event.ACTIVE_REAGENT, function(para)
        -- 初始化数据
        self:initData();

        -- 默认选中页签1
        self:initTabs();
        self:selectTab(self.tabList[1]:getTag());
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UIReagent");

            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                uiForm:showBottomMenu();
            end

            local uiForm = UIMgr.getCurrentScene():getFormByName("UICarriableItem");
            if uiForm then
                uiForm:setVisible(true);
            end
        elseif eventType == "enter" then
            local uiForm = UIMgr.getCurrentScene():getFormByName("UINewWorkshop");
            if uiForm then
                uiForm:hideBottomMenu();
            end

            local uiForm = UIMgr.getCurrentScene():getFormByName("UICarriableItem");
            if uiForm then
                uiForm:setVisible(false);
            end
        end
    end);
end

-- 注册点击事件
function UIReagent:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIReagent");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 当商品被点击
function UIReagent:onGoodsClick(iconImg)
    -- 显示商品详细信息
    UIMgr.getCurrentScene():removeFormByName("UIReagentDetail");
    local uiGoodsDetail = UIReagentDetail.create(iconImg.goodsIndex);
    UIMgr.getCurrentScene():addForm(uiGoodsDetail);
end

-- 关闭购买商品的消息
function UIReagent:whenBuyGoods(classId, amount)
    -- 提示玩家购买了商品
    local function delay()
        local name  = ItemM.query(classId, "name");
        alert(string.format(getLocStr("modulation_goods_done"), name, amount));
    end

    performWithDelay(self, delay, 0.1);
end


